import * as React from "react";
import * as monacoGlobal from "monaco-editor";
import SplitPane from "react-split-pane";
import "./SpitEditor.css"; // 假设你有一个单独的 CSS 文件来定义样式

import { EditorPane } from "./EditorPane";
import { GraphPane } from "./GraphPane";
import { SupportedFormat, SupportedEngine } from "../rendering";
import { getSplitConfig, saveSplitConfig } from "../config";

type ErrorList = monacoGlobal.editor.IMarkerData[];

interface Props {
	initialSource: string;
	format: SupportedFormat;
	engine: SupportedEngine;
	onSourceChange?(source: string): void;
}

type State = SourceState | ErroredState;
interface SourceState {
	dotSrc: string;
	errors: undefined;
	lastKnownGoodSrc: undefined;
	showModal: boolean; // 控制弹出层显示/隐藏的状态
	isClickAccept: boolean; // 是否点击同意
	modalMessage: string; // 弹出层的提示信息
}
interface ErroredState {
	dotSrc: undefined;
	errors: ErrorList;
	lastKnownGoodSrc?: string;
	showModal: boolean;
	isClickAccept: boolean; // 是否点击同意
	modalMessage: string;
}

const createSourceState = (dotSrc: string): SourceState => ({
	dotSrc,
	errors: undefined,
	lastKnownGoodSrc: undefined,
	showModal: false,
	isClickAccept: false,
	modalMessage: ""
});
const createErroredState = (
	errors: ErrorList,
	lastKnownGoodSrc?: string
): ErroredState => ({
	dotSrc: undefined,
	errors,
	lastKnownGoodSrc,
	showModal: false,
	isClickAccept: false,
	modalMessage: ""
});
let _dotSrc: any = "graph G {\n" +
	"\t55135 [label=\"35kV迁巩线312开关\" color=\"#FFFF00\" fillcolor=gray fontcolor=black shape=rectangle style=\"bold,filled\"]\n" +
	"\t12240 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t72448 [label=AF_25 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
	"\t12243 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t60135 [label=\"35kV迁巩线31237地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
	"\t12246 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t47979 [label=\"35kV迁巩线3123刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
	"\t12241 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t72449 [label=AF_27 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
	"\t12244 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t60136 [label=\"35kV迁巩线31217地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
	"\t12247 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t47980 [label=\"35kV迁巩线3121刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
	"\t55135 -- 12240 [color=\"#FFFF00\"]\n" +
	"\t55135 -- 12241 [color=\"#FFFF00\"]\n" +
	"\t12240 -- 72448 [color=\"#FFFF00\"]\n" +
	"\t72448 -- 12243 [color=\"#FFFF00\"]\n" +
	"\t72448 -- 12246 [color=\"#FFFF00\"]\n" +
	"\t12243 -- 60135 [color=\"#FFFF00\"]\n" +
	"\t12246 -- 47979 [color=\"#FFFF00\"]\n" +
	"\t12241 -- 72449 [color=\"#FFFF00\"]\n" +
	"\t72449 -- 12247 [color=\"#FFFF00\"]\n" +
	"\t72449 -- 12244 [color=\"#FFFF00\"]\n" +
	"\t12244 -- 60136 [color=\"#FFFF00\"]\n" +
	"\t12247 -- 47980 [color=\"#FFFF00\"]\n" +
	"}\n";
export default class SplitEditor extends React.Component<Props, State> {
	private editorPaneRef: React.RefObject<EditorPane> = React.createRef();

	constructor(props: Props) {
		super(props);
		const p = this.props;

		this.state = createSourceState(p.initialSource);
		if (p.onSourceChange)
			p.onSourceChange(this.state.dotSrc);
	}

	public loadDotSource(dotSrc: string) {
		const editor = this.editorPaneRef.current;
		if (editor) {
			editor.loadValue(dotSrc);
		}
	}

	dotSourceChanged = (dotSrc: string): void => {
		const p = this.props;
		if (p.onSourceChange)
			p.onSourceChange(dotSrc);

		this.setState(createSourceState(dotSrc));
	};

	dotSourceErrored = (errors: ErrorList): void => {
		this.setState(prevState => {
			const lastKnownGoodSrc = prevState.dotSrc || prevState.lastKnownGoodSrc;
			return createErroredState(errors, lastKnownGoodSrc);
		});
	};

	private getDotSrcToRender() {
		const s = this.state;

		return !!s.dotSrc
			? s.dotSrc
			: s.lastKnownGoodSrc
				? s.lastKnownGoodSrc
				: "";
	}

	private changeNodeValue() {
		const that = this;
		interface ChangeValue {
			oneValue: string, // 鼠标点击第一个值
			twoValue: string, // 鼠标点击第二个值
			isComplete: Boolean // 是否这个已经完成，如果已经完成，就把上面两个值清空
		}
		let changeValue:ChangeValue = { // 改变的值
			oneValue: '', // 鼠标点击第一个值
			twoValue: '', // 鼠标点击第二个值
			isComplete: false // 是否这个已经完成，如果已经完成，就把上面两个值清空
		}
		let oldValue:any = undefined; // 上一次点击的值，防止用户重复点击
		let stepNum:number = 0; //默认0，完成第一个值，就是1

		// const setDotInfoTop = setTimeout(()=>{
		// 	window.clearTimeout(setDotInfoTop);
		// 	that.setState(createSourceState(_dotSrc));
		// },200)
		// 获取所有 class 为 node 的节点
		const clickTimeout = setTimeout( ()=>{
			const nodeElements = document.querySelectorAll('.node');
			window.clearTimeout(clickTimeout)
			// 为每个节点添加点击事件监听器
			nodeElements.forEach((node) => {
				node.addEventListener("click", () => {
					let _dotSrc:any = that.state.dotSrc; //获取当前值
					let _dotSrcStorage:any = window.localStorage.getItem('_dotSrc'); //获取当前值
					let isHasValue:boolean = false;

					const titleElement = node.querySelector("title");
					if (titleElement) {
						const startValue:any = titleElement.textContent;



						let lines:any = undefined; //重新切割的数据
						let newString:any = undefined; //最后返回的新的字符

						const match:any = _dotSrc.match(/\t(\d+)\s+\[/);
						// if (match) {
						// 	const firstValue:any = match[1];
						// 	if(firstValue === startValue){ //如果是最顶部的值，则不做处理
						// 		return;
						// 	}
						//
						// } else {
						// 	console.log("未找到符合条件的值");
						// }

						if(_dotSrc.indexOf(startValue + ' --') > -1){ //如果存在，就是删除

							isHasValue = true;
						}
						if(isHasValue){ //如果存在，就是删除
							lines = _dotSrc.split('\n');
						}else{
							lines = _dotSrcStorage.split('\n');
						}

						const graph:any = {};
						// 构建图的邻接表
						lines.forEach((line: { includes: (arg0: string) => any; split: (arg0: string) => { (): any; new(): any; map: { (arg0: (part: any) => any): [any, any]; new(): any; }; }; }) => {
							if (line.includes('--')) {
								const [from, to] = line.split('--').map(part => part.trim().split(' ')[0]);
								if (!graph[from]) {
									graph[from] = [];
								}
								graph[from].push(to);
							}
						});

						const visited = new Set();
						const relevantValues:any = []; //搜索出来的，用于删除数据
						const relevantLines:any = []; //查出来的新的，用于添加数据
						// 深度优先搜索函数
						function dfs(node:any) {
							if (visited.has(node)) return;
							visited.add(node);
							relevantValues.push(node);
							if (graph[node]) {
								graph[node].forEach((neighbor: any) => {
									dfs(neighbor);
								});
							}
						}
						dfs(startValue);


						if(isHasValue){ //如果存在，就是删除
							console.log(lines)
							console.log(relevantValues)
							// const newLines = lines.filter((line: string | any[]) => {
							// 	return!relevantValues.some((value: string) => line.includes(value));
							// });
							let newLines = lines.filter((line: string | string[]) => {
								return!relevantValues.some((value: string) => {
									return line.includes(value + ' -- ') || line.includes('\t' + value + ' [label=');
								});
							});

							let closeStyle:any=null;

							for (const line of lines) {
								if (line.includes(`\t${startValue} `)) {
									closeStyle = line;
									break;
								}
							}

							// 指定插入的位置（索引）
							const insertIndex = 1;


							let array = [1, 2, 4, 5];
							let elementToAdd = 3; // 要插入的元素

							// 使用slice()分割数组，然后使用concat()重新组合
							let firstPart = newLines.slice(0, insertIndex); // 从开始到指定位置之前的部分
							let secondPart = newLines.slice(insertIndex);   // 从指定位置到数组末尾的部分

							// 在分割后的数组之间插入元素
							const newLines22:any = firstPart.concat([closeStyle]).concat(secondPart);

							console.log(array); // 输出: [1, 2, 3, 4, 5]

							// 使用splice方法插入数据
							// newLines.splice(insertIndex, 1, closeStyle);

							newString = newLines22.join('\n');
						}else{


							lines.forEach((line: string | string[]) => {
								if (relevantValues.some((value: string) => {
									return line.includes(value + ' -- ') || line.includes('\t' + value + ' [label=');
								})) {
									relevantLines.push(line);
								}
							});


							const resultVariable = relevantLines.join('\n');
							const endIndex = _dotSrc.lastIndexOf('}'); // 拼接字符串
							newString = _dotSrc.slice(0, endIndex) + "\n" + resultVariable + "\n" + "}";

						}



						const setDotInfo = setTimeout(()=>{
							window.clearTimeout(setDotInfo);
							console.log('newString', newString);
							that.setState(createSourceState(""));
							that.setState(createSourceState(newString));
							if(isHasValue){
								that.setState({
									showModal: true,
									modalMessage: `${startValue} 收缩成功`
								});
							}else{
								if(relevantLines.length > 1){
									that.setState({
										showModal: true,
										modalMessage: `${startValue} 展开成功`
									});
								}
							}
							const changeB = setTimeout(() => { //重新给dom树绑定点击事件
								window.clearTimeout(changeB);
								that.changeNodeValue();
							}, 200);

							const changeB2 = setTimeout(() => {
								window.clearTimeout(changeB2);
								that.setState({
									showModal: false,
									modalMessage: `关闭`
								});
							}, 1200);

						},600)


						// return
						// if (titleValue!== oldValue) {
						// 	if (stepNum === 0) {
						// 		if (typeof titleValue === "string") {
						// 			changeValue.oneValue = titleValue;
						// 			oldValue = titleValue;
						// 			stepNum = 1;
						// 		}
						// 		// 显示弹出层并设置提示信息
						// 		that.setState({
						// 			showModal: true,
						// 			modalMessage: `${changeValue.oneValue} 设定为【起始线】成功`
						// 		});
						// 		const setDotInfoOne = setTimeout(()=>{
						// 			window.clearTimeout(setDotInfoOne);
						// 			that.setState({showModal: false})
						// 		},1800)
						// 	} else if (stepNum === 1) {
						// 		if (typeof titleValue === "string") {
						// 			changeValue.twoValue = titleValue;
						// 			oldValue = titleValue;
						// 			stepNum = 2;
						// 		}
						// 		let _dotSrc: any = "graph G {\n" +
						// 			"\t55135 [label=\"35kV迁巩线312开关\" color=\"#FFFF00\" fillcolor=gray fontcolor=black shape=rectangle style=\"bold,filled\"]\n" +
						// 			"\t12240 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t72448 [label=AF_25 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
						// 			"\t12243 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t60135 [label=\"35kV迁巩线31237地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
						// 			"\t12246 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t47979 [label=\"35kV迁巩线3123刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
						// 			"\t12241 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t72449 [label=AF_27 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
						// 			"\t12244 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t60136 [label=\"35kV迁巩线31217地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
						// 			"\t12247 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t47980 [label=\"35kV迁巩线3121刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
						// 			"\t55135 -- 12240 [color=\"#FFFF00\"]\n" +
						// 			"\t55135 -- 12241 [color=\"#FFFF00\"]\n" +
						// 			"\t12240 -- 72448 [color=\"#FFFF00\"]\n" +
						// 			"\t72448 -- 12243 [color=\"#FFFF00\"]\n" +
						// 			"\t72448 -- 12246 [color=\"#FFFF00\"]\n" +
						// 			"\t12243 -- 60135 [color=\"#FFFF00\"]\n" +
						// 			"\t12246 -- 47979 [color=\"#FFFF00\"]\n" +
						// 			"\t12241 -- 72449 [color=\"#FFFF00\"]\n" +
						// 			"\t72449 -- 12247 [color=\"#FFFF00\"]\n" +
						// 			"\t72449 -- 12244 [color=\"#FFFF00\"]\n" +
						// 			"\t12244 -- 60136 [color=\"#FFFF00\"]\n" +
						// 			"\t12247 -- 47980 [color=\"#FFFF00\"]\n" +
						// 			"}\n";
						// 		// let _dotSrc: any = that.state.dotSrc;
						// 		const colorRegex = /color="([^"]+)"/;
						// 		const match = _dotSrc.match(colorRegex);
						// 		let color;
						// 		if (match) {
						// 			color = match[1];
						// 		} else {
						// 			color = "#000000";
						// 		}
						//
						// 		// 构建新的边信息
						// 		const newEdge = `\t${changeValue.oneValue} -- ${changeValue.twoValue} [color="${color}"]\n`;
						//
						// 		// 在 dotSrc 字符串的倒数第二个字符（即 '}' 之前）插入新的边信息
						// 		_dotSrc = _dotSrc.slice(0, -2) + newEdge + _dotSrc.slice(-2);
						//
						// 		// debugger
						// 		// 显示弹出层并设置提示信息
						// 		that.setState({
						// 			showModal: true,
						// 			modalMessage: `${changeValue.twoValue} 设定为【终止线】成功`
						// 		});
						//
						// 		const setDotInfo = setTimeout(()=>{
						// 			window.clearTimeout(setDotInfo);
						// 			that.setState(createSourceState(""));
						// 			that.setState(createSourceState(_dotSrc));
						//
						// 			const changeB = setTimeout(() => {
						// 				window.clearTimeout(changeB);
						// 				that.changeNodeValue();
						// 			}, 200);
						// 		},1800)
						//
						//
						// 	}
						// }
					}
					console.log(changeValue);
				});
			});
		}, 1000);
	}

	public componentDidMount() {
		this.changeNodeValue();
		window.localStorage.setItem('_dotSrc', _dotSrc) //先存一次
		this.setState(createSourceState(_dotSrc));
	}

	// 关闭弹出层的方法
	closeModal = () => {
		this.setState({ showModal: false });
		this.setState({ isClickAccept: false });
	};

	// 取消按钮的点击处理方法
	handleCancel = () => {
		this.closeModal();
		this.setState({ isClickAccept: false });
	};

	// 确定按钮的点击处理方法
	handleConfirm = () => {
		this.closeModal();
		this.setState({ isClickAccept: true });
		// 这里可以添加确定按钮的其他逻辑
	};

	public render() {
		const s = this.state;
		const p = this.props;
		const that = this;

		const isErrored = s.errors && s.errors.length > 0;
		const dotSrc = this.getDotSrcToRender();

		var messageHandle = function (e: any) {
			let dotSrc = e.data
			console.log("接受到的信息是：" + e.data);
			let dotSrc22 = encodeURIComponent(`"# Place the cursor inside "graph" to get some refactoring options

      graph {

        # To refactor nodes, place the cursor left to a node name
        a -- b
        a -- c;
        a -- d;
        a -- b;
        a -- ec;

        # Hover over color names to get a color picker
        b -- b [color=blue]
        b -- d [color="#ff0000"];

        # Get completion when assigning a shape or color
        b [shape=box, color=yellow];

        a; # You can remove optional ; by placing the cursor left to a semicolon
      }
      "`);
			that.setState(createSourceState(dotSrc));
			that.changeNodeValue();
		};

		if (window.addEventListener) {
			window.addEventListener("message", messageHandle, false);
		}


		const graphPaneClass = isErrored? "errored" : "successful";

		return (
			<div>
				<SplitPane
					split="vertical"
					minSize={50}
					defaultSize={getSplitConfig() || "50%"}
					onChange={size => saveSplitConfig(size)}
				>
					<EditorPane
						ref={this.editorPaneRef}
						defaultValue={s.dotSrc}
						onChangeValue={this.dotSourceChanged}
						onValueError={this.dotSourceErrored}
					/>
					<GraphPane
						className={"graph-container " + graphPaneClass}
						dotSrc={dotSrc}
						engine={p.engine}
						format={p.format}
					/>
				</SplitPane>
				{/* 弹出层 */}
				{s.showModal && (
					<div className="modal-overlay">
						<div className="modal">
							<div className="modal-header">
								<span className="modal-title">提示</span>
								{/*<span className="close-button" onClick={this.closeModal}>&times;</span>*/}
							</div>
							<div className="modal-body">{s.modalMessage}</div>
							{/*<div className="modal-footer">*/}
							{/*	<button className="cancel-button" onClick={this.handleCancel}>*/}
							{/*		取消*/}
							{/*	</button>*/}
							{/*	<button className="confirm-button" onClick={this.handleConfirm}>*/}
							{/*		确定*/}
							{/*	</button>*/}
							{/*</div>*/}
						</div>
					</div>
				)}
			</div>
		);
	}
}
